﻿using CKS.Core.Framework;
using CKS.PLC.Action.System;
using FreeSql;
using MySqlX.XDevAPI.Relational;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP20
{
    public class DB3021_CncA_UploadAction : SaveProcessingResults
    {
        /// <summary>
        /// CNC：A面,加工状态变化上传
        /// </summary>
        /// <param name="_value"></param>
        public DB3021_CncA_UploadAction(DecodeValue _value) : base(_value)
        {
        }

        public override AfterSaveResult AfterSaved(SaveArg e)
        {
            /*
            Value.Position.LocationId  { 1 : op10 2:op20 3 op30}

            XxxTask 
            Code = Value.GetLocationData(mainRecord.LocationId, 1).ToString();
            LocationId = Value.Position.LocationId 
            TaskStatus = 0 
            SaveTask

         */
            
            string coverCode = Value.GetLocationData(e.LocationId, 1).ToString();
            var record = new CksProductionRecord()
            {
                CoverCode = coverCode,
                ASideMachineNumber = Value.GetLocationData(e.LocationId, 2).ToInt(),
                ASideToolingNumber = Value.GetLocationData(e.LocationId, 3).ToInt(),
                UploadStatus = Value.GetLocationData(e.LocationId, 4).ToInt()
            };
            ProcessData(record);

            return base.AfterSaved(e);

        }

        private void ProcessData(CksProductionRecord data)
        {
            if (data.CoverCode.IsEmpty())
                return;

            var record = GetRecordByCoverCode(data.CoverCode);
            record.CoverCode = data.CoverCode;
            record.ASideMachineNumber = data.ASideMachineNumber;
            record.ASideToolingNumber = data.ASideToolingNumber;
            string tag = "";
            switch (data.UploadStatus)
            {
                case 1:
                    record.ProcessingStatus = 1;
                    record.ASideLoadingTime = DateTime.Now;
                    tag = "投入";
                    break;
                case 2:
                    record.ProcessingStatus = 2;
                    record.ASideStartTime = DateTime.Now;
                    tag = "开始";
                    break;
                case 3:
                    record.ProcessingStatus = 3;
                    record.ASideEndTime = DateTime.Now;
                    tag = "结束";
                    break;
                case 4:
                    record.ProcessingStatus = 4;
                    record.ASideUnloadingTime = DateTime.Now;
                    tag = "取出";
                    break;
                default:
                    EventBus.AddLog($"CNC_A面 {record.CoverCode} 上传状态未知 {data.UploadStatus}");
                    return; 
            }


            
            if (record.Id > 0)
                conn.Update<CksProductionRecord>()
                    .SetSource(record)
                    .UpdateColumns(a => new { a.CoverCode ,a.ASideMachineNumber,a.ProcessingStatus ,
                        a.ASideToolingNumber,a.ASideLoadingTime ,a.ASideStartTime ,a.ASideEndTime ,a.ASideUnloadingTime
                        }).ExecuteAffrows();
            else
            {
                // 格式示例 PW 250624 0001  
                string dayCacheKey = $"PW{DateTime.Now.ToString("yyMMdd")}";
                var nextSeriaNumber = GetNextSerialNumber(dayCacheKey);
                record.SerialNumber = $"{dayCacheKey}{nextSeriaNumber.ToString().PadLeft(4, '0')}";
                conn.Insert(record).ExecuteAffrows();
                conn.Update<CksKeyCache>()
                    .Set(a => a.MaxSerialNumber, nextSeriaNumber)
                   .Where(a => a.CacheKey == dayCacheKey).ExecuteAffrows();

            }
            EventBus.AddLog($"CNC_A面_{tag}；工站：OP20;{record.CoverCode} 保存完成  ");

        }

        private CksProductionRecord GetRecordByCoverCode(string coverCode)
        {
            var record = conn.Select<CksProductionRecord>()
                .Where(a => a.CreatedTime > DateTime.Now.AddYears(-1) && a.CoverCode == coverCode).OrderByDescending(a => a.Id).First();
            if (record == null)
                record = new CksProductionRecord();
            return record;
        }
    }
}
